//  BackView.m
//
//  a View that provides some functionality that some screen savers might
//  find useful; you can subclass this class if you like.
//
//  You may freely copy, distribute, and reuse the code in this example.
//  NeXT disclaims any warranty of any kind, expressed or  implied, as to its
//  fitness for any particular use.

#import "BackView.h"
#import "Thinker.h"
#import <appkit/NXImage.h>
#import <dpsclient/wraps.h>
#import <libc.h>

@implementation BackView

- (BOOL) timePassed: (BStimeval) delay
{
	BStimeval now, msec;
	BOOL result;
	
	now = currentTimeInMs();
	if (BVthen == 0)		// added by shou-h@nexus.or.jp
	    BVthen = now;		// added by shou-h@nexus.or.jp
	msec = now - BVthen;

	//so as not to suck too many cycles, if I'm waiting for some
	// time more than a tenth of a second in the future, I sleep
	// a while.  This interval is short enough that the app shouldn't
	// seem unresponsive to user actions.
	
	// ok, so you'd never pull this trick if the user had to type.
	// A better solution would be to coordinate the timed entry better,
	// but I get slightly better performance from spinning in my
	// timed entry (a bad idea for most apps...)
	
	if ((msec + 120) < delay)
	{	usleep(110000);
		return NO;
	}
	
	result = (msec > delay);
	if (result) BVthen = now;

	return result;
}

- initFrame:(const NXRect *)frameRect
{
	[super initFrame:frameRect];
	[self allocateGState];		// For faster lock/unlockFocus

	srandom(time(0));

	[self setImageConstraints];
	return self;
}

- sizeTo:(NXCoord)width :(NXCoord)height
{
	[super sizeTo:width :height];
	[self setImageConstraints];
	return self;
}

- drawSelf:(const NXRect *)rects :(int)rectCount
{
	if (!rects || !rectCount) return self;

	PSsetgray(0);
	NXRectFill(rects);

	return self;
}

- setImageConstraints
{
	maxCoord.x = bounds.size.width - imageRect.size.width;
	maxCoord.y = bounds.size.height - imageRect.size.height;
	if (maxCoord.x < 0) maxCoord.x = 0;
	if (maxCoord.y < 0) maxCoord.y = 0;

	return self;
}


- setImage: newImage
{
	image = newImage;
	[image getSize: &imageRect.size];

	[self setImageConstraints];
	[self display];

	return self;
}

- (BOOL) useBufferedWindow
{
	return YES; // by default; can be overridden in subclasses
}

@end
